import React, { useState, useRef } from "react";
import useStyles from "./style";
import { flushSync } from "react-dom";

interface CatList {
  id: number;
  imageUrl: string;
}
const catList: CatList[] = [];
for (let i = 0; i < 10; i++) {
  catList.push({
    id: i,
    imageUrl: "https://placekitten.com/250/200?image=" + i
  });
}
const CatsFriendsThree: React.FC = () => {
  const [index, setIndex] = useState(0);
  const { ul, nav } = useStyles();
  const selectedRef = useRef<HTMLLIElement>(null);

  return (
    <>
      <nav className={nav}>
        <button
          onClick={() => {
            flushSync(() => {
              if (index < catList.length - 1) {
                setIndex(index + 1);
              } else {
                setIndex(0);
              }
            });

            selectedRef.current?.scrollIntoView({
              behavior: "smooth",
              block: "nearest",
              inline: "nearest"
            });
          }}
        >
          下一个
        </button>
      </nav>
      <ul className={ul}>
        {catList.map((cat, i) => (
          <li key={cat.id} ref={index === i ? selectedRef : null}>
            <img className={index === i ? "active" : ""} src={cat.imageUrl} alt={"猫猫 #" + cat.id} />
          </li>
        ))}
      </ul>
    </>
  );
};
export default CatsFriendsThree;
